/*
 * Backup tool for system database
 * Backup filename convention is backup-<yyyy>-<mm>-<dd>-<incrementNum>.sql
 */
package org.dbdir.core;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.dbdir.Server;
import org.dbdir.core.helper.Date;

/**
 *
 * @author thotheolh
 */
public class Backup {

    private String bkpath = "backup";
    private String backupName = "backup";
    private Date currentDate = new Date();
    private int day;
    private int mth;
    private int yr = 0;
    private int currDay = currentDate.getDay();
    private int currMth = currentDate.getMonth();
    private int currYr = currentDate.getYear();
    private int currIncrementNum,  biggestIncNum,  smallestIncNum = 0;
    private Connection conn;
    private Server server;

    public Backup(Server server, Connection conn) {
        this.checkDir();
        this.getLatestBackupNum();
        this.conn = conn;
        this.server = server;
    }

    public void getLatestBackupNum() {
        File file = new File(this.getBkpath());
        String[] filelist = file.list();
        if (filelist.length > 0) {
            for (int i = 0; i < filelist.length; i++) {
                String currFileName = filelist[i].toString();
                String[] filename = currFileName.split("\\.");
                String[] fields = filename[0].split("-");
                if (fields[0].equals(getBackupName())) {
                    setYr(Integer.parseInt(fields[1].toString()));
                    setMth(Integer.parseInt(fields[2].toString()));
                    setDay(Integer.parseInt(fields[3].toString()));
                    this.checkFields(fields[4].toString());
                }
            }
        }
    }

    /**
     * @return the currIncrementNum
     */
    public int getCurrIncrementNum() {
        return currIncrementNum;
    }

    /**
     * @param currIncrementNum the currIncrementNum to set
     */
    public void setCurrIncrementNum(int currIncrementNum) {
        this.currIncrementNum = currIncrementNum;
    }

    private void checkDir() {
        File dir = new File(this.getBkpath());
        if (!dir.exists()) {
            dir.mkdir();
        }
    }

    /**
     * @return the biggestIncNum
     */
    public int getBiggestIncNum() {
        return biggestIncNum;
    }

    /**
     * @param biggestIncNum the biggestIncNum to set
     */
    public void setBiggestIncNum(int biggestIncNum) {
        this.biggestIncNum = biggestIncNum;
    }

    /**
     * @return the smallestIncNum
     */
    public int getSmallestIncNum() {
        return smallestIncNum;
    }

    /**
     * @param smallestIncNum the smallestIncNum to set
     */
    public void setSmallestIncNum(int smallestIncNum) {
        this.smallestIncNum = smallestIncNum;
    }

    private void checkFields(String currNum) {
        if ((this.getDay() == this.getDay()) && (this.getMth() == this.getCurrMth()) && (this.getYr() == this.getCurrYr())) {
            this.setCurrIncrementNum(Integer.parseInt(currNum));
            if (this.getCurrIncrementNum() > this.getBiggestIncNum()) {
                this.setBiggestIncNum(this.getCurrIncrementNum());
            }
        }
    }

    /**
     * @return the bkpath
     */
    public String getBkpath() {
        return bkpath;
    }

    /**
     * @param bkpath the bkpath to set
     */
    public void setBkpath(String bkpath) {
        this.bkpath = bkpath;
    }

    /**
     * @return the backupName
     */
    public String getBackupName() {
        return backupName;
    }

    /**
     * @param backupName the backupName to set
     */
    public void setBackupName(String backupName) {
        this.backupName = backupName;
    }

    /**
     * @return the currentDate
     */
    public Date getCurrentDate() {
        return currentDate;
    }

    /**
     * @param currentDate the currentDate to set
     */
    public void setCurrentDate(Date currentDate) {
        this.currentDate = currentDate;
    }

    /**
     * @return the day
     */
    public int getDay() {
        return day;
    }

    /**
     * @param day the day to set
     */
    public void setDay(int day) {
        this.day = day;
    }

    /**
     * @return the mth
     */
    public int getMth() {
        return mth;
    }

    /**
     * @param mth the mth to set
     */
    public void setMth(int mth) {
        this.mth = mth;
    }

    /**
     * @return the yr
     */
    public int getYr() {
        return yr;
    }

    /**
     * @param yr the yr to set
     */
    public void setYr(int yr) {
        this.yr = yr;
    }

    /**
     * @return the currDay
     */
    public int getCurrDay() {
        return currDay;
    }

    /**
     * @param currDay the currDay to set
     */
    public void setCurrDay(int currDay) {
        this.currDay = currDay;
    }

    /**
     * @return the currMth
     */
    public int getCurrMth() {
        return currMth;
    }

    /**
     * @param currMth the currMth to set
     */
    public void setCurrMth(int currMth) {
        this.currMth = currMth;
    }

    /**
     * @return the currYr
     */
    public int getCurrYr() {
        return currYr;
    }

    /**
     * @param currYr the currYr to set
     */
    public void setCurrYr(int currYr) {
        this.currYr = currYr;
    }

    public boolean doBackup() {
        try {
            this.setBiggestIncNum(this.getBiggestIncNum()+1);
            String backupAbstractPath = this.getBkpath()+"/"+this.getBackupName()+"-"+this.currYr+"-"+this.currMth+"-"+this.currDay+"-"+this.getBiggestIncNum()+".sql";
            File backupAbsolutePath = new File(backupAbstractPath).getAbsoluteFile();
            String statement = "SCRIPT TO '"+backupAbsolutePath.getPath()+"'";
            System.out.println("Backing up to: "+backupAbsolutePath.getPath());
            PreparedStatement pstmt = conn.prepareStatement(statement);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                System.out.println("Backup completed !");
                return true;
            }
        } catch (SQLException ex) {
            server.getLog().log(2, ex.getMessage());
        }
        return false;
    }

    private void testFilePath() {
        try {
            File testfile = new File("test.txt");
            testfile.createNewFile();
            System.out.println(testfile.getAbsoluteFile());
        } catch (IOException ex) {
            server.getLog().log(2, ex.getMessage());
        }

    }
}
